package com.sg.common.empty.core;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.sg.activiti.service.MyActivitiService;
import com.sg.common.empty.entity.PerfProperty;
import com.sg.common.empty.json.AttaList;
import com.sg.common.empty.json.Permission;
import com.sg.common.empty.json.SecList;
import com.sg.common.empty.json.SectionDraw;
import com.sg.common.empty.json.SectionListDraw;
import com.sg.common.empty.service.CfgService;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.ReUtils;

public class EditFormBuilder {
	String url;
	Object bean;
	Map<String, Object> map=new HashMap<String, Object>();
	private String route;
	Object tableBean;
	private CfgService service;
	private MyActivitiService actiService;
	List<Object> listBean;
//	Perf perf;
	String beanId;
	String ids;
	List<Permission> specialPermission;
	List<Permission> perfPermission;
	String enctype;
	List<SectionDraw> sds;
	SecList[] sls;
	AttaList attaList;
	List<SectionListDraw> slds;
	String taskId;

	public void init(HttpServletRequest request) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
//		taskId = request.getParameter("_taskId");
		url = request.getRequestURI();
//		bean = request.getAttribute("bean");
//		tableBean = request.getAttribute("tableBean");
//		perf = (Perf) request.getAttribute("perf");
		beanId = request.getParameter("id");
		ids = request.getParameter("ids");
//		specialPermission = (List<Permission>) request
//				.getAttribute("specialPermission");
//		perfPermission = (List<Permission>) request
//				.getAttribute("perfPermission");
	}
//
//	public StringBuilder neditForm() throws ClassNotFoundException,
//			SecurityException, NoSuchFieldException, IllegalArgumentException,
//			IllegalAccessException, InvocationTargetException,
//			NoSuchMethodException {
//		StringBuilder res = new StringBuilder();
//		// 用于判断是否增加流程发送按钮
//		int send = sendType(tableBean, bean);
//		StringBuilder sendBut = new StringBuilder();
//		if (send != 0) {
//			if (send == 1) {
//				sendBut.append("<script type='text/javascript' src='js/acti/start.js'></script>");
//				String className = ReUtils.getStr(tableBean, "className");
//				String editUri = url + "?id=" + beanId;
//				sendBut.append(
//						"<ul class='nav'><li><a href='javascript:void(0)' onclick='start(\"")
//						.append(className).append("\",\"").append(beanId)
//						.append("\",\"").append(editUri)
//						.append("\")'></i>启动流程</a></li></ul>");
//			} else if (send == 2 || send == 3) {
//				sendBut.append("<script type='text/javascript' src='js/acti/comp.js'></script>");
//				sendBut.append("<ul class='nav'><li><a href='javascript:void(0)' onclick='acti_open()'></i>发送流程</a></li></ul>");
//				if (send == 3) {
//					String taskId = ReUtils.getStr(bean, "taskId");
//					sendBut.append("<script type='text/javascript' src='js/acti/cancel.js'></script>");
//					sendBut.append(
//							"<ul class='nav'><li><a href='javascript:void(0)' onclick='acti_cancel(\"")
//							.append(taskId)
//							.append("\")'></i>取消流程</a></li></ul>");
//				}
//			}
//		}
//		JspUtil3.fixTop(url, beanId, ids, res, JspUtil3.buttons(sendBut)
//				.toString(), perf.getId(), specialPermission, perfPermission);
//		StringBuilder formTitle = JspUtil3.formTitle(url, enctype);
//		res.append(formTitle);
//		JspUtil3.drawLayoutSecTable(bean, res, sds);
//
//		JspUtil3.drawLayoutAttaList(bean, res, attaList);
//
//		res.append(drawLayoutSecListTable());
//
//		if (send == 2 || send == 3) {
//			List<String> trans = actiService.getOutGoingTransNames(taskId);
//			res.append("<div id='dd' title='流程发送' style='width:450px;height:300px;left:300px;top:150px;padding:10px' toolbar='#dlg-toolbar' buttons='#dlg-buttons' resizable='true'>");
//			if (trans != null && trans.size() > 1) {
//				res.append("去向：");
//				for (String tran : trans) {
//					res.append("<input type='radio' value='").append(tran)
//							.append("' name='agree'>").append(tran);
//				}
//			}
//			res.append("<br/>审核意见：<input id='checkAdvice' type='text'>");
//			res.append("<input id='taskId' type='hidden' value='" + taskId
//					+ "'> </div>");
//		}
//		res.append("</form>");
//
//		// 流程历史查看
//		SecList[] nsls = EpUtil.flowAttachment(tableBean);
//
//		JspUtil3.drawLayoutSecList(bean, res, sls, nsls);
//
//		return res;
//	}
//

	public StringBuilder emptyNeditForm() throws ClassNotFoundException,
			SecurityException, NoSuchFieldException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		StringBuilder res = new StringBuilder();
		
//		JspUtil3.fixTop(url, beanId, ids, res, JspUtil3.buttons(null)
//				.toString(), perf.getId(), specialPermission, perfPermission);
		JspUtil3.emptyFixTop(getRoute(), beanId, ids, res, JspUtil3.buttons(null)
				.toString());
		StringBuilder formTitle = JspUtil3.formTitle(url, enctype);
		res.append(formTitle);
		JspUtil3.emptyDrawLayoutSecTable(map, res, sds);

		res.append("</form>");

		return res;
	}
	
	private int sendType(Object tableBean, Object bean)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		int send = 0;
		if (ReUtils.get(tableBean, "isFlow").equals("1")) {
			String beanTaskId = ReUtils.getStr(bean, "taskId");
			String beanTaskKey = ReUtils.getStr(bean, "taskKey");
			if (StringUtils.isEmpty(beanTaskId)) {
				send = 1;// 有流程但未启动
			} else if (StringUtils.isNotEmpty(beanTaskId)
					&& StringUtils.isNotEmpty(taskId)) {
				if (!StringUtils.equals(beanTaskKey, "apply")
						&& !StringUtils.equals(beanTaskKey, "taskover")) {
					send = 2;// 有流程且已启动，并且不是第一个也不是最后一个
				} else if (StringUtils.equals(beanTaskKey, "apply")) {
					send = 3;// 有流程且已启动，也是第一个
				}
			}
		}
		return send;
	}

//	public StringBuilder seditForm() throws ClassNotFoundException,
//			SecurityException, NoSuchFieldException, IllegalArgumentException,
//			IllegalAccessException, InvocationTargetException,
//			NoSuchMethodException {
//		StringBuilder res = new StringBuilder();
//		JspUtil3.fixTop(url, beanId, ids, res, JspUtil3.buttons(null)
//				.toString(), perf.getId(), specialPermission, perfPermission);
//		StringBuilder formTitle = JspUtil3.formTitle(url, enctype);
//		res.append(formTitle);
//		res.append(drawLayoutSelectListTable());
//		// 增加页面标志位，设定此页面为多行编辑页面
//		res.append("<input type='hidden' name='_editsflag' value='1'></input></form>");
//		return res;
//	}

	/**
	 * 创建bean的property批量更新
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 */
	private StringBuilder drawLayoutSelectListTable()
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, ClassNotFoundException, SecurityException,
			IllegalArgumentException, NoSuchFieldException {
		StringBuilder res = new StringBuilder();
		if (!CollUtil.isNotEmpty(sds) && !CollUtil.isNotEmpty(listBean))
			return res;
		for (SectionDraw sd : sds) {
			JspUtil3.buildTogTitle(sd.getTitle(), sd.getBk(), res);
			// Object refObj = ReUtils.get(bean, ref);
			// refObj.getClass().getComponentType();

			// 得到关联属性的值列表
			// DetachedCriteria dc =
			// DetachedCriteria.forClass(Class.forName(ref));//TODO
			// dc.add(Restrictions.eq(sld.getJoinColumn(), ReUtils.getStr(bean,
			// sld.getRefColumn())));
			// if(StringUtils.isNotEmpty(sld.getSqlFilter()))
			// dc.add(Restrictions.sqlRestriction(sld.getSqlFilter()));

			// draw by all_edit方式
			List<PerfProperty> pps = sd.getPps();
			if (CollUtil.isNotEmpty(pps)) {
				// 画一个table
				res.append(JspUtil3.ADD_EDIT_TABLE);
				// head
				res.append("<tr>");
				for (PerfProperty pp : pps) {
					if (!"0".equals(pp.getEsh())) {
						res.append("<td>").append(pp.getProperty().getDescr())
								.append("</td>");
					}
				}
				res.append("</tr>");
				// body
				int ind = 0;
				for (Object obj : listBean) {
					res.append("<tr>");
					for (PerfProperty pp : pps) {
						String[] beanValue = JspUtil3.filedVal(obj, pp);
						StringBuilder value = new MyinputBuilder(pp, beanValue,
								true, "bean[" + ind + "]").findInput();
						if (!"0".equals(pp.getEsh())) {
							res.append("<td>").append(value).append("</td>");
						} else {
							res.append(value);
						}
					}
					res.append("</tr>");
					ind++;
				}
				res.append("</table>");
			}
		}
		return res;
	}

	/**
	 * 创建bean的property批量更新
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 */
	private StringBuilder drawLayoutSecListTable()
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, ClassNotFoundException, SecurityException,
			IllegalArgumentException, NoSuchFieldException {
		StringBuilder res = new StringBuilder();
		if (!CollUtil.isNotEmpty(slds))
			return res;
		for (SectionListDraw sld : slds) {
			JspUtil3.buildTogTitle(sld.getTitle(), res);
			// Object refObj = ReUtils.get(bean, ref);
			// refObj.getClass().getComponentType();

			// 得到关联属性的值列表
			// DetachedCriteria dc =
			// DetachedCriteria.forClass(Class.forName(ref));//TODO
			// dc.add(Restrictions.eq(sld.getJoinColumn(), ReUtils.getStr(bean,
			// sld.getRefColumn())));
			// if(StringUtils.isNotEmpty(sld.getSqlFilter()))
			// dc.add(Restrictions.sqlRestriction(sld.getSqlFilter()));
			DetachedCriteria dc = DetachedCriteria.forClass(Class.forName(sld
					.getRefClass()));
			dc.add(Restrictions.eq(sld.getJoinColumn(), bean));
			List<Object> refList = getService().find(dc);

			// draw by all_edit方式
			List<PerfProperty> pps = sld.getPps();
			if (CollUtil.isNotEmpty(pps)) {
				// 画一个table
				res.append(JspUtil3.ADD_EDIT_TABLE);
				// head
				res.append("<tr>");
				for (PerfProperty pp : pps) {
					if (!"0".equals(pp.getEsh())) {
						res.append("<td>").append(pp.getProperty().getDescr())
								.append("</td>");
					}
				}
				res.append("</tr>");
				// body
				int ind = 0;
				for (Object obj : refList) {
					res.append("<tr>");
					for (PerfProperty pp : pps) {
						String[] beanValue = JspUtil3.filedVal(obj, pp);
						StringBuilder value = new MyinputBuilder(pp, beanValue,
								true, sld.getRef() + "[" + ind + "]")
								.findInput();
						if (!"0".equals(pp.getEsh())) {
							res.append("<td>").append(value).append("</td>");
						} else {
							res.append(value);
						}
					}
					res.append("</tr>");
					ind++;
				}
				res.append("</table>");
			}
		}
		return res;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Object getBean() {
		return bean;
	}

	public void setBean(Object bean) {
		this.bean = bean;
	}

//	public Perf getPerf() {
//		return perf;
//	}
//
//	public void setPerf(Perf perf) {
//		this.perf = perf;
//	}

	public String getBeanId() {
		return beanId;
	}

	public void setBeanId(String beanId) {
		this.beanId = beanId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public List<Permission> getSpecialPermission() {
		return specialPermission;
	}

	public void setSpecialPermission(List<Permission> specialPermission) {
		this.specialPermission = specialPermission;
	}

	public List<Permission> getPerfPermission() {
		return perfPermission;
	}

	public void setPerfPermission(List<Permission> perfPermission) {
		this.perfPermission = perfPermission;
	}

	public String getEnctype() {
		return enctype;
	}

	public void setEnctype(String enctype) {
		this.enctype = enctype;
	}

	public List<SectionDraw> getSds() {
		return sds;
	}

	public void setSds(List<SectionDraw> sds) {
		this.sds = sds;
	}

	public SecList[] getSls() {
		return sls;
	}

	public void setSls(SecList[] sls) {
		this.sls = sls;
	}

	public List<SectionListDraw> getSlds() {
		return slds;
	}

	public void setSlds(List<SectionListDraw> slds) {
		this.slds = slds;
	}

	public CfgService getService() {
		return service;
	}

	public void setService(CfgService service) {
		this.service = service;
	}

	public List<Object> getListBean() {
		return listBean;
	}

	public void setListBean(List<Object> listBean) {
		this.listBean = listBean;
	}

	public MyActivitiService getActiService() {
		return actiService;
	}

	public void setActiService(MyActivitiService actiService) {
		this.actiService = actiService;
	}

	public AttaList getAttaList() {
		return attaList;
	}

	public void setAttaList(AttaList attaList) {
		this.attaList = attaList;
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}

	public String getRoute() {
		return route;
	}

	public void setRoute(String route) {
		this.route = route;
	}
	
}
